package nckd.wnqjt.tmc.tda.plugin.form;

import kd.bos.algo.DataSet;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.report.AbstractReportListDataPlugin;
import kd.bos.entity.report.FilterInfo;
import kd.bos.entity.report.FilterItemInfo;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhujintao
 * @date 2024/11/05
 * @desc 金融机构授信
 */
public class FinanceOrgCreditListDataPlugin extends AbstractReportListDataPlugin {

    @Override
    public DataSet query(ReportQueryParam reportQueryParam, Object o) throws Throwable {
        // 借款单位
        FilterInfo filterInfo = reportQueryParam.getFilter();
        FilterItemInfo org = filterInfo.getFilterItem("nckd_org");
        Object value = org.getValue();
        DynamicObjectCollection nckdOrg = null;
        if (value != null) {
            nckdOrg = (DynamicObjectCollection) value;
        }
        // 查询日期
        FilterItemInfo querydate = filterInfo.getFilterItem("nckd_querydate");
        String selectField = "id,banktype,bank,bank.bank_cate.id bankbankcateid,org,totalamt,useamt,enddate,entry_type.t_credittype.fbasedataid.id credittype,entry_type.t_totalamt allocationamt,entry_type.t_useamt usedamt";
        //授信结束日期>当前日期前一个月月底的授信额度管理单
        //获取当前日期，用于计算3个月的日期
        LocalDate currentDate = LocalDate.now();
        //这个地方处理querydate，但是感觉没必要，就当前日期的好了


        int currentMonth = currentDate.getMonthValue();
        //设置当前日期为上个月的第一天
        int lastMonth = (currentMonth == 1) ? 12 : currentMonth - 1;
        LocalDate firstDayOfLastMonth = currentDate.withMonth(lastMonth).withDayOfMonth(1);
        //获取上个月的最后一天
        LocalDate lastDayOfLastMonth = firstDayOfLastMonth.plusMonths(1).minusDays(1);
        //格式化日期为所需的格式
        Date enddate = Date.from(lastDayOfLastMonth.atTime(0, 0, 0).atZone(ZoneId.systemDefault()).toInstant());
        //Date enddate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        QFilter filter = new QFilter("status", QCP.equals, "C").and("isclose",QCP.equals,false)
                .and("enddate", QCP.large_than, enddate);
        if (nckdOrg != null) {
            List<Long> longList = nckdOrg.stream().map(e -> e.getLong("id")).collect(Collectors.toList());
            filter.and("org", QCP.in, longList);
        }
        DataSet dataSet = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cfm_creditlimit", selectField, filter.toArray(), null);
        //求和项:综合授信合计：总授信额度； 求和项:授信使用情况合计：已用额度；
        DataSet group1 = dataSet.copy().select("id", "banktype", "bank", "bankbankcateid", "org", "totalamt", "useamt").distinct().groupBy(new String[]{"banktype", "bank", "bankbankcateid", "org"}).sum("totalamt").sum("useamt").finish();
        //求和项:其中银行贷款：授信类别为流动资金贷款的分配额度；
        //求和项:银行敞口：授信类别为银行承兑汇票的分配额度；
        //求和项:其中：银行贷款使用额：授信类别为流动资金贷款的已用额度；
        //求和项:银行敞口使用额：授信类别为银行承兑汇票的已用额度；
        DynamicObject SX0002 = BusinessDataServiceHelper.loadSingle("cfm_credittype", "id", new QFilter[]{new QFilter("number", QCP.equals, "SX0002")});
        DynamicObject SX0003 = BusinessDataServiceHelper.loadSingle("cfm_credittype", "id", new QFilter[]{new QFilter("number", QCP.equals, "SX0003")});
        String filterSX0002 = "credittype == " + SX0002.getLong("id");
        String filterSX0003 = "credittype == " + SX0003.getLong("id");
        //授信类别为流动资金贷款
        DataSet group2 = dataSet.copy().filter(filterSX0002).groupBy(new String[]{"bank", "bankbankcateid", "org"}).sum("allocationamt").sum("usedamt").finish();
        //授信类别为银行承兑汇票
        DataSet group3 = dataSet.copy().filter(filterSX0003).groupBy(new String[]{"bank", "bankbankcateid", "org"}).sum("allocationamt").sum("usedamt").finish();
        DataSet finish = group1.leftJoin(group2).on("bank", "bank").on("bankbankcateid", "bankbankcateid").on("org", "org").select(group1.getRowMeta().getFieldNames(), new String[]{"allocationamt as flowallocationamt", "usedamt as flowusedamt"}).finish();
        DataSet finish1 = finish.leftJoin(group3).on("bank", "bank").on("bankbankcateid", "bankbankcateid").on("org", "org").select(finish.getRowMeta().getFieldNames(), new String[]{"allocationamt as draftallocationamt", "usedamt as draftusedamt"}).finish();
        finish1 = finish1.updateField("totalamt", "totalamt / 10000");//---
        finish1 = finish1.updateField("flowallocationamt", "flowallocationamt / 10000");//---
        finish1 = finish1.updateField("draftallocationamt", "draftallocationamt / 10000");//---
        finish1 = finish1.updateField("useamt", "useamt / 10000");//---
        finish1 = finish1.updateField("flowusedamt", "flowusedamt / 10000");//----
        finish1 = finish1.updateField("draftusedamt", "draftusedamt / 10000");//---
        return finish1.orderBy(new String[]{"bankbankcateid","org"});
    }
}